package edu.pku.sei.act.classGenerator;

import edu.pku.sei.act.taskStruct.*;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;

 public class TaskProcessorClassGenerator {  
  protected static String nl;
  public static synchronized TaskProcessorClassGenerator create(String lineSeparator)
  {
    nl = lineSeparator;
    TaskProcessorClassGenerator result = new TaskProcessorClassGenerator();
    nl = null;
    return result;
  }

  public final String NL = nl == null ? (System.getProperties().getProperty("line.separator")) : nl;
  protected final String TEXT_1 = "";
  protected final String TEXT_2 = NL + NL + "package edu.pku.sei.act.";
  protected final String TEXT_3 = ";" + NL + "" + NL + "import edu.pku.sei.act.actools.ICapabilityManager;" + NL + "import edu.pku.sei.act.actools.IEnvEntry;" + NL + "import edu.pku.sei.act.actools.ITask;" + NL + "import edu.pku.sei.act.actools.util.ACToolsNamingSpace;" + NL + "import edu.pku.sei.act.actools.util.AbilityOutput;" + NL + "import edu.pku.sei.act.actools.util.CapabilityMap;" + NL + "import edu.pku.sei.act.actools.util.EnvInfo;" + NL + "import edu.pku.sei.act.actools.util.Role;" + NL + "import edu.pku.sei.act.actools.util.Task;" + NL + "import edu.pku.sei.act.actools.util.TaskMessage;";
  protected final String TEXT_4 = "\t" + NL + "import edu.pku.sei.act.";
  protected final String TEXT_5 = ".";
  protected final String TEXT_6 = ".";
  protected final String TEXT_7 = ";";
  protected final String TEXT_8 = NL + "import android.app.Service;" + NL + "import android.content.ComponentName;" + NL + "import android.content.Context;" + NL + "import android.content.Intent;" + NL + "import android.content.ServiceConnection;" + NL + "import android.os.IBinder;" + NL + "import android.os.RemoteException;" + NL + "import android.util.Log;" + NL + "" + NL + "public class ";
  protected final String TEXT_9 = " extends Service {" + NL + "\t" + NL + "\tprivate static ICapabilityManager cm;" + NL + "\tprivate static IEnvEntry ee;" + NL + "\tprivate static Task task;" + NL + "\tprivate static String currentState;" + NL + "\tprivate static final String RECEIVER_INIT = \"edu.pku.sei.act.";
  protected final String TEXT_10 = ".";
  protected final String TEXT_11 = "\";" + NL + "\tprivate static final String INIT_STATE = \"";
  protected final String TEXT_12 = "\";" + NL + "\tprivate ServiceConnection CMConnection = new ServiceConnection() {" + NL + "" + NL + "\t\tpublic void onServiceConnected(ComponentName arg0, IBinder arg1) {" + NL + "\t\t\t" + NL + "\t\t\tcm = ICapabilityManager.Stub.asInterface(arg1);" + NL + "\t\t}" + NL + "" + NL + "\t\tpublic void onServiceDisconnected(ComponentName name) {" + NL + "\t\t\t" + NL + "\t\t\tcm = null;" + NL + "\t\t}" + NL + "\t};" + NL + "\t" + NL + "\tprivate ServiceConnection EEConnection = new ServiceConnection() {" + NL + "" + NL + "\t\tpublic void onServiceConnected(ComponentName arg0, IBinder arg1) {" + NL + "\t\t\tee = IEnvEntry.Stub.asInterface(arg1);" + NL + "\t\t\ttry {" + NL + "\t\t\t\t//ee.notifyLWrite(task.getDescriptor(), 0, -1);" + NL + "\t\t\t\tsetState(INIT_STATE);" + NL + "\t\t\t} catch (RemoteException e) {" + NL + "\t\t\t\te.printStackTrace();" + NL + "\t\t\t}" + NL + "\t\t}" + NL + "" + NL + "\t\tpublic void onServiceDisconnected(ComponentName name) {" + NL + "\t\t\tee = null;" + NL + "\t\t}" + NL + "\t};" + NL + "\t" + NL + "\tprivate  final ITask.Stub mbinder = new ITask.Stub() {" + NL + "\t\t" + NL + "\t\tpublic boolean playRole(String role) throws RemoteException {" + NL + "\t\t" + NL + "\t\t";
  protected final String TEXT_13 = NL + "\t\t\tif(role.equals(\"";
  protected final String TEXT_14 = "\")) {\t\t\t\t" + NL + "\t\t\t\tCapabilityMap map = new CapabilityMap();" + NL + "\t\t\t\tmap.setTaskID(task.getTaskName()+\"$\"+";
  protected final String TEXT_15 = ".ROLE_NAME);" + NL + "\t\t\t\tmap.setProviderID(ACToolsNamingSpace.ACToolsComponent.CAPABILITY_PROVIDER);" + NL + "\t\t\t\t";
  protected final String TEXT_16 = NL + "\t\t\t\t" + NL + "\t\t\t\t" + NL + "\t\t\t\tmap.setTaskAbility(";
  protected final String TEXT_17 = ".capability.";
  protected final String TEXT_18 = ".getAbilityName());" + NL + "\t\t\t\tmap.setType(";
  protected final String TEXT_19 = ".capability.";
  protected final String TEXT_20 = ".getType());\t\t\t\t" + NL + "\t\t\t\tmap.setProviderAbility(\"";
  protected final String TEXT_21 = "\");" + NL + "\t\t\t\tee.LWrite(EnvInfo.HEAD_TUPLE + \",\" + map, 0, -1);" + NL + "\t\t\t\t" + NL + "\t\t\t\t";
  protected final String TEXT_22 = NL + "\t\t\t\t\tString s = cm.invokeCapability(";
  protected final String TEXT_23 = ".capability.";
  protected final String TEXT_24 = ", null);" + NL + "\t\t\t\t\tLog.v(\"@";
  protected final String TEXT_25 = "!";
  protected final String TEXT_26 = " template\",s);\t\t\t\t" + NL + "\t\t\t\t\t";
  protected final String TEXT_27 = ".capability.";
  protected final String TEXT_28 = " = new AbilityOutput(s);" + NL + "\t\t\t\t" + NL + "\t\t\t\t";
  protected final String TEXT_29 = NL + "\t\t\t\t" + NL + "\t\t\t\t";
  protected final String TEXT_30 = "\t\t\t \t\t\t\t" + NL + "\t\t\t\tsetState(";
  protected final String TEXT_31 = ".state.";
  protected final String TEXT_32 = ");" + NL + "\t\t\t}" + NL + "\t\t";
  protected final String TEXT_33 = NL + "\t\t\treturn true;" + NL + "\t\t}" + NL + "\t\t" + NL + "\t\tpublic void interupt() throws RemoteException {" + NL + "\t\t\t" + NL + "\t\t}" + NL + "\t\t" + NL + "\t\tpublic String getTaskDescriptor() throws RemoteException {" + NL + "\t\t\treturn task.getDescriptor();" + NL + "\t\t}" + NL + "\t};" + NL + "" + NL + "\tpublic void onCreate() {" + NL + "\t\tsuper.onCreate();" + NL + "\t\t" + NL + "\t\ttask = new Task();" + NL + "\t\ttask.setTaskName(\"";
  protected final String TEXT_34 = "\");" + NL + "\t\t" + NL + "\t\t" + NL + "\t\tfinal Intent serviceIntent1 = new Intent();" + NL + "        serviceIntent1.setAction(ACToolsNamingSpace.ACToolsComponent.CAPABILITY_MANAGER);" + NL + "        bindService(serviceIntent1,CMConnection,Context.BIND_AUTO_CREATE);" + NL + "        " + NL + "        final Intent serviceIntent2 = new Intent();" + NL + "        serviceIntent2.setAction(ACToolsNamingSpace.ACToolsComponent.ENV_ENTRY);" + NL + "        bindService(serviceIntent2,EEConnection,Context.BIND_AUTO_CREATE);" + NL + "        " + NL + "\t}" + NL + "\t" + NL + "" + NL + "\t@Override" + NL + "\tpublic void onDestroy() {" + NL + "\t\tsuper.onDestroy();" + NL + "\t\tunbindService(CMConnection);" + NL + "\t\tunbindService(EEConnection);" + NL + "\t}" + NL + "" + NL + "" + NL + "\t@Override" + NL + "\tpublic IBinder onBind(Intent intent) {" + NL + "\t\treturn mbinder;" + NL + "\t}" + NL + "" + NL + "\tpublic static Task getTask() {" + NL + "\t\treturn task;" + NL + "\t}" + NL + "" + NL + "\tpublic static ICapabilityManager getCm() {" + NL + "\t\treturn cm;" + NL + "\t}" + NL + "" + NL + "\tpublic static IEnvEntry getEe() {" + NL + "\t\treturn ee;" + NL + "\t}" + NL + "\t" + NL + "\tpublic static void setState(String state) throws RemoteException {" + NL + "\t\tLog.v(\"@";
  protected final String TEXT_35 = "  STATE:\",state);" + NL + "\t\tcurrentState = state;" + NL + "\t\tTaskMessage msg = new TaskMessage();" + NL + "\t\tmsg.setTaskName(task.getTaskName());" + NL + "\t\tee.LTakeMany(EnvInfo.HEAD_READ_TEMPLATE + \",\" + msg);" + NL + "\t\tee.LTakeMany(EnvInfo.HEAD_TAKE_TEMPLATE + \",\" + msg);" + NL + "\t\tee.RTakeMany(EnvInfo.HEAD_READ_TEMPLATE + \",\" + msg);" + NL + "\t\tee.RTakeMany(EnvInfo.HEAD_TAKE_TEMPLATE + \",\" + msg);" + NL + "\t\t" + NL + "\t\t";
  protected final String TEXT_36 = NL + "\t\t\t\t\t\tee.LTake(EnvInfo.HEAD_TAKE_TEMPLATE + \",\" + ";
  protected final String TEXT_37 = ".capability.";
  protected final String TEXT_38 = ";\t\t" + NL + "\t\t";
  protected final String TEXT_39 = NL + "\t\t\t\t\t\t\t\t\t\t\t" + NL + "\t\tif(state.equals(INIT_STATE)) {" + NL + "\t\t\tmsg.setTopic(ACToolsNamingSpace.EnvInfo.PLAY_ROLE);" + NL + "\t\t\tee.notifyLWrite(EnvInfo.HEAD_TAKE_TEMPLATE+ \"$\" + RECEIVER_INIT + \",\" + msg,0,-1);" + NL + "\t\t}" + NL + "\t\t" + NL + "\t\t";
  protected final String TEXT_40 = NL + "\t\t\t\t\telse if(state.equals(";
  protected final String TEXT_41 = ".state.";
  protected final String TEXT_42 = "))" + NL + "\t\t\t\t\t{" + NL + "\t\t\t\t\t" + NL + "\t\t\t\t\t";
  protected final String TEXT_43 = NL + "\t\t\t\t\t  \tee.notifyLWrite(EnvInfo.HEAD_READ_TEMPLATE + \"$\" + ";
  protected final String TEXT_44 = ".transformation.";
  protected final String TEXT_45 = " + \",\" + new CapabilityMap(), 0, 0);" + NL + "\t\t\t\t\t  ";
  protected final String TEXT_46 = NL + "\t\t\t\t\t   \t\t\tmsg = ";
  protected final String TEXT_47 = ".communication.";
  protected final String TEXT_48 = ";" + NL + "\t\t\t\t\t\t\t\tmsg.setReceiver(ee.getIdentity());" + NL + "\t\t\t\t\t\t\t\tee.RWrite(EnvInfo.HEAD_TAKE_TEMPLATE + \"$\" + ";
  protected final String TEXT_49 = ".transformation.";
  protected final String TEXT_50 = " + \",\" + msg, 0, -1);\t\t\t\t\t\t\t\t\t\t\t\t" + NL + "\t\t\t\t\t   ";
  protected final String TEXT_51 = "\t\t\t\t\t  \t" + NL + "\t\t\t\t\t\t\t\t\tee.LWrite(EnvInfo.HEAD_TAKE_TEMPLATE + \"$\" + ";
  protected final String TEXT_52 = ".transformation.";
  protected final String TEXT_53 = " + \",\" + ";
  protected final String TEXT_54 = ".capability.";
  protected final String TEXT_55 = ", 0, -1);" + NL + "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" + NL + "\t\t\t\t\t";
  protected final String TEXT_56 = NL + "\t\t\t\t\t}" + NL + "\t\t\t\t\t\t\t\t\t\t\t" + NL + "\t\t";
  protected final String TEXT_57 = "\t\t\t\t" + NL + "\t}" + NL + "" + NL + "\tpublic static String getCurrentState() {" + NL + "\t\treturn currentState;" + NL + "\t}" + NL + "" + NL + "}";
  protected final String TEXT_58 = NL;

 public String generate(Task task)
  {
    final StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append(TEXT_1);
    
Collection<Role> roles = task.getRoles();
String taskProcessorName = NameGenerator.genTaskProcessorName(task.getName());

    stringBuffer.append(TEXT_2);
    stringBuffer.append( NameGenerator.genTaskPackageName(task.getName()));
    stringBuffer.append(TEXT_3);
     for(Iterator<Role> it = roles.iterator(); it.hasNext(); ) 
	{
		Role role = it.next();

    stringBuffer.append(TEXT_4);
    stringBuffer.append( NameGenerator.genTaskPackageName(task.getName()));
    stringBuffer.append(TEXT_5);
    stringBuffer.append( NameGenerator.genRolePackageName(role.getName()));
    stringBuffer.append(TEXT_6);
    stringBuffer.append( NameGenerator.genRoleName(role.getName()));
    stringBuffer.append(TEXT_7);
    	}
 
    stringBuffer.append(TEXT_8);
    stringBuffer.append( taskProcessorName);
    stringBuffer.append(TEXT_9);
    stringBuffer.append( NameGenerator.genTaskName(task.getName()));
    stringBuffer.append(TEXT_10);
    stringBuffer.append( NameGenerator.genTransitionName(task.getInitTrans().getName()));
    stringBuffer.append(TEXT_11);
    stringBuffer.append( NameGenerator.genStateName(task.getInitState().getName()));
    stringBuffer.append(TEXT_12);
     for(Iterator<Role> it = roles.iterator(); it.hasNext(); )
			{
				Role role = it.next();
				String roleName = NameGenerator.genRoleName(role.getName()); 
		 
    stringBuffer.append(TEXT_13);
    stringBuffer.append( roleName);
    stringBuffer.append(TEXT_14);
    stringBuffer.append( roleName);
    stringBuffer.append(TEXT_15);
    
				 Collection<Capability> caps = role.getCapabilities();
				 for(Iterator<Capability> it2 = caps.iterator(); it2.hasNext(); )
				 { 
				 	Capability cap = it2.next();
				 	String capName = NameGenerator.genCapabilityName(cap.getName());
				
    stringBuffer.append(TEXT_16);
    stringBuffer.append( roleName);
    stringBuffer.append(TEXT_17);
    stringBuffer.append( capName);
    stringBuffer.append(TEXT_18);
    stringBuffer.append( roleName);
    stringBuffer.append(TEXT_19);
    stringBuffer.append( capName);
    stringBuffer.append(TEXT_20);
    stringBuffer.append( capName);
    stringBuffer.append(TEXT_21);
     if(NameGenerator.DEAMON.equals(NameGenerator.genCapabilityTypeName(cap.getType())))
					{
				
    stringBuffer.append(TEXT_22);
    stringBuffer.append( roleName);
    stringBuffer.append(TEXT_23);
    stringBuffer.append( capName);
    stringBuffer.append(TEXT_24);
    stringBuffer.append( taskProcessorName);
    stringBuffer.append(TEXT_25);
    stringBuffer.append( NameGenerator.genAbilityOutputName(cap.getName()));
    stringBuffer.append(TEXT_26);
    stringBuffer.append( roleName);
    stringBuffer.append(TEXT_27);
    stringBuffer.append( NameGenerator.genAbilityOutputName(cap.getName()));
    stringBuffer.append(TEXT_28);
      }
				 } 
    stringBuffer.append(TEXT_29);
     Collection<State> states = role.getStates();
					State postState = null;
					for(Iterator<State> it3 = states.iterator(); it3.hasNext(); )
					{
						State state = it3.next();
						Set<String> preTransIds = state.getPreTransIds();
						for(String id : preTransIds)
						{
							if(task.getInitTrans().getId().equals(id))
							{
								postState = state;
								break;
							}
						}						
						if(postState != null) break;
					}
					String postStateName = "";
					if(postState != null) postStateName = NameGenerator.genStateName(postState.getName());								
				
    stringBuffer.append(TEXT_30);
    stringBuffer.append( roleName);
    stringBuffer.append(TEXT_31);
    stringBuffer.append( postStateName);
    stringBuffer.append(TEXT_32);
    
		}
		
    stringBuffer.append(TEXT_33);
    stringBuffer.append( taskProcessorName);
    stringBuffer.append(TEXT_34);
    stringBuffer.append( taskProcessorName);
    stringBuffer.append(TEXT_35);
     for(Iterator<Role> it = roles.iterator(); it.hasNext(); )
			{
				Role role = it.next();
				Collection<Capability> caps = role.getCapabilities();
				for(Iterator<Capability> it2 = caps.iterator(); it2.hasNext(); )
				{
					Capability cap = it2.next();
					if(NameGenerator.DEAMON.equals(NameGenerator.genCapabilityTypeName(cap.getType())))
					{
		
    stringBuffer.append(TEXT_36);
    stringBuffer.append( NameGenerator.genRoleName(role.getName()));
    stringBuffer.append(TEXT_37);
    stringBuffer.append(NameGenerator.genAbilityOutputName(cap.getName()));
    stringBuffer.append(TEXT_38);
      		}
				}
			}
		
    stringBuffer.append(TEXT_39);
     for(Iterator<Role> it = roles.iterator(); it.hasNext(); )
			{
				Role role = it.next();
				Collection<State> states = role.getStates();
				String roleName = NameGenerator.genRoleName(role.getName());
				for(Iterator<State> it2 = states.iterator(); it2.hasNext(); )
				{
					State state = it2.next();
					Set<String> postTransIds = state.getPostTransIds();				
		
    stringBuffer.append(TEXT_40);
    stringBuffer.append( roleName);
    stringBuffer.append(TEXT_41);
    stringBuffer.append( NameGenerator.genStateName(state.getName()));
    stringBuffer.append(TEXT_42);
    for(Iterator<String> it3 = postTransIds.iterator(); it3.hasNext(); )
					  {
					  	String id = it3.next();
					  	Transition trans = role.getTransById(id);
					  	if(trans != null)
					  	{
					  	String transName = NameGenerator.genTransitionName(trans.getName());					  						
					  	String preMsgId = trans.getPreTaskMessageId();
					  	String abilityOutputId = trans.getAbilityOutputId();
					  	if(NameGenerator.genTransitionTypeName("trigByDelay").equals(trans.getType()))
					  	{ 
					  
    stringBuffer.append(TEXT_43);
    stringBuffer.append(roleName);
    stringBuffer.append(TEXT_44);
    stringBuffer.append(transName);
    stringBuffer.append(TEXT_45);
     } else if(preMsgId != "")
					  	 {  
					  	    TaskMessage msg = role.getTaskMessageById(preMsgId);					  	    
					  		if(msg != null)
					  		{				  		
					  		  String msgName = NameGenerator.genTaskMessageName(msg.getName());					  			   
					   
    stringBuffer.append(TEXT_46);
    stringBuffer.append(roleName);
    stringBuffer.append(TEXT_47);
    stringBuffer.append(msgName);
    stringBuffer.append(TEXT_48);
    stringBuffer.append(roleName);
    stringBuffer.append(TEXT_49);
    stringBuffer.append(transName);
    stringBuffer.append(TEXT_50);
     	}
					   	  } else if(abilityOutputId != null)
					   	  	{
					   	  		Capability cap = role.getCapabilityById(abilityOutputId);					   	  		
					   	  		if(cap != null)
					   	  		{
					   	  			String abilityOutputName = NameGenerator.genAbilityOutputName(cap.getName());
					   	
    stringBuffer.append(TEXT_51);
    stringBuffer.append(roleName);
    stringBuffer.append(TEXT_52);
    stringBuffer.append(transName);
    stringBuffer.append(TEXT_53);
    stringBuffer.append(roleName);
    stringBuffer.append(TEXT_54);
    stringBuffer.append(abilityOutputName);
    stringBuffer.append(TEXT_55);
      		}
							}
						}
					  } 
    stringBuffer.append(TEXT_56);
    		}
			}
		
    stringBuffer.append(TEXT_57);
    stringBuffer.append(TEXT_58);
    return stringBuffer.toString();
  }
}